package com.ds.infra.ibatis.demo.config;

import com.ds.infra.ibatis.demo.mapper.UserMapper;
import com.ds.infra.ibatis.demo.model.User;
import com.ds.infra.ibatis.mapping.MappedStatement;
import com.ds.infra.ibatis.mapping.SqlCommandType;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

/**
 * 作用： 配置Mapper扫描器，手动注册所有Mapper接口。
 *
 * @author WeiShaoying
 */
@Configuration
public class MapperScannerConfig {

    @Resource
    private com.ds.infra.ibatis.session.Configuration configuration;

    @PostConstruct
    public void registerMappers() {
        try {
            // 简单方式：手动注册所有Mapper接口
            configuration.addMapper(UserMapper.class);
            // 添加其他Mapper接口...
        } catch (Exception e) {
            throw new RuntimeException("Failed to register mappers", e);
        }
    }

    @Deprecated
    private void registerUserMapper() {
        // 注册Mapper接口
        configuration.addMapper(UserMapper.class);

        // 手动添加MappedStatement
        addMappedStatement("com.ds.infra.ibatis.mapper.UserMapper.selectAll", "SELECT * FROM user", SqlCommandType.SELECT, User.class);
        addMappedStatement("com.ds.infra.ibatis.mapper.UserMapper.selectById", "SELECT * FROM user WHERE id = #{id}", SqlCommandType.SELECT, User.class);

        addMappedStatement("com.ds.infra.ibatis.mapper.UserMapper.insert",
                "INSERT INTO user(name, age, email) VALUES(#{name}, #{age}, #{email})",
                SqlCommandType.INSERT, Integer.class);

        addMappedStatement("com.ds.infra.ibatis.mapper.UserMapper.update",
                "UPDATE user SET name=#{name}, age=#{age}, email=#{email} WHERE id=#{id}",
                SqlCommandType.UPDATE, Integer.class);

        addMappedStatement("com.ds.infra.ibatis.mapper.UserMapper.deleteById",
                "DELETE FROM user WHERE id=#{id}", SqlCommandType.DELETE, Integer.class);
    }

    //  添加MappedStatement
    private void addMappedStatement(String id, String sql, SqlCommandType sqlCommandType, Class<?> resultType) {
        MappedStatement ms = new MappedStatement();
        ms.setId(id);
        ms.setSql(sql);
        ms.setSqlCommandType(sqlCommandType);
        ms.setResultType(resultType);
        configuration.addMappedStatement(ms);
    }
}
